<template>
	<view>
		<view>
			<view class="search" v-if="search_btn">
				<view @tap="openSearch">
					<icon type="search" size="12"></icon>
					<text>搜索</text>
				</view>
			</view>
		</view>

		<view class="main_body">
			<view>
				<!-- 左侧列表内容部分 -->
				<scroll-view :class="
            'content ' + (gotop ? (isIPX ? 'goTopX' : 'goTop') : 'goback')
          " enable-back-to-top :scroll-into-view="toView" scroll-y="true" scroll-with-animation="true"
					:style="'padding-bottom: ' + (isIPX ? '270rpx' : '226rpx')">
					<!-- search -->

					<view class="search_input" v-if="search_friend">
						<view>
							<icon type="search" size="13"></icon>
							<input placeholder="搜索" placeholder-style="color:#CFCFCF;line-height:20px;font-size:12px;"
								auto-focus confirm-type="search" type="text" @confirm="onSearch" @input="onInput"
								:value="input_code" />
							<icon type="clear" size="13" @tap.stop="clearInput" v-if="show_clear"></icon>
						</view>
						<text @tap="cancel">取消</text>
					</view>
					<view class="contain">
						<view class="otherItem" @tap="add_new">
							<image src="/static/images/invite_theme2x.png" data-username="name"></image>
							<text>添加好友</text>
						</view>
						<view class="otherItem" @tap="into_groups">
							<image src="/static/images/groupTheme.png"></image>
							<text>群组</text>
						</view>
					</view>

					<view v-for="(group, id) in listMain" :key="id" :id="'inToView' + group.id" :data-id="group.id">
						<view class="address_top">{{ group.region }}</view>
						<view v-for="(item, brandId) in group.brands" :key="brandId" :data-username="item.name"
							@tap.stop="delete_friend">
							<swipe-delete>
								<view class="tap_mask" @tap.stop="into_room" :data-username="item.name"
									:data-yournickname="item.yournickname">
									<view class="address_bottom" :data-username="item.name"
										:data-yournickname="item.yournickname" @tap.stop="into_room">
										<image :src="getAvatarurl(item)" @tap.stop="into_room"
											:data-username="item.name" :data-yournickname="item.yournickname"></image>
										<text @tap.stop="into_room" :data-username="item.name"
											:data-yournickname="item.yournickname">
											{{getNickName(item)}} </text>
									</view>
								</view>
							</swipe-delete>
						</view>
					</view>
				</scroll-view>
				<!-- 右侧字母导航 -->
				<view class="orientation_region">
					<block v-for="(item, id) in listMain" :key="id">
						<view :class="
                'orientation_city ' + (isActive == item.id ? 'active' : '')
              " @tap="scrollToViewFn" :data-id="item.id">{{ item.region }}</view>
					</block>
				</view>
			</view>
		</view>

		<!--   <view :class="isIPX ? 'chatRoom_tab_X' : 'chatRoom_tab'">
      <view class="tableBar" @tap="tab_chat">
        <view
          v-if="unReadSpotNum > 0 || unReadSpotNum == '99+'"
          :class="
            'em-unread-spot ' +
            (unReadSpotNum == '99+' ? 'em-unread-spot-litleFont' : '')
          "
          >{{ unReadSpotNum == '99+'?unReadSpotNum:unReadSpotNum+ unReadTotalNotNum }}</view
        >
        <image
          :class="unReadSpotNum > 0 || unReadSpotNum == '99+' ? 'haveSpot' : ''"
          src="/static/images/session2x.png"
        ></image>
        <text>消息</text>
      </view>

      <view class="tableBar">
        <image src="/static/images/comtactshighlight2x.png"></image>
        <text class="activeText">联系人</text>
      </view>


      <view class="tableBar" @tap="tab_setting">
        <image src="/static/images/setting2x.png"></image>
        <text>我的</text>
      </view>
    </view> -->
	</view>
</template>

<script>
	let WebIM = require("../../utils/WebIM")["default"];
	let disp = require("../../utils/broadcast");
	let systemReady = false;
	let canPullDownreffesh = true;
	let oHeight = [];
	import swipeDelete from "../../components/swipedelete/swipedelete";

	export default {
		data() {
			return {
				search_btn: true,
				search_friend: false,
				show_mask: false,
				myName: "",
				member: [],
				messageNum: "",
				//加好友申请数
				unReadSpotNum: 0,
				//未读消息数
				unReadNoticeNum: 0,
				//加群通知数
				unReadTotalNotNum: 0,
				//总通知数：加好友申请数 + 加群通知数
				isActive: null,
				listMain: [],
				listTitles: [],
				toView: "inToView0",
				oHeight: [],
				scroolHeight: 0,
				show_clear: false,
				isHideLoadMore: true,
				isIPX: false,
				gotop: false,
				input_code: "",
				showFixedTitile: false,
			};
		},

		components: {
			swipeDelete,
		},
		props: {},

		onLoad(option) {
			var login=this.checkLogin();
			if(!login)
			{
				return false;
			}
			option.myName = uni.getStorageSync("myUsername");
			
			const me = this;
			const app = getApp().globalData;
			//监听加好友申请


			disp.on("em.subscribe", function() {
				me.setData({
					messageNum: getApp().globalData.saveFriendList.length,
					unReadTotalNotNum: getApp().globalData.saveFriendList.length +
						getApp().globalData.saveGroupInvitedList.length,
				});
			});
			disp.on("em.contacts.remove", function(message) {
				var pageStack = getCurrentPages();

				if (pageStack[pageStack.length - 1].route === me.__route__) {
					me.getRoster();
				}
			}); //监听未读“聊天”

			disp.on("em.unreadspot", function() {
				me.setData({
					unReadSpotNum: getApp().globalData.unReadMessageNum > 99 ?
						"99+" : getApp().globalData.unReadMessageNum,
				});
			}); //监听未读加群“通知”数

			disp.on("em.invite.joingroup", function() {
				me.setData({
					unReadNoticeNum: getApp().globalData.saveGroupInvitedList.length,
					unReadTotalNotNum: getApp().globalData.saveFriendList.length +
						getApp().globalData.saveGroupInvitedList.length,
				});
			});
			disp.on("em.subscribed", function() {
				var pageStack = getCurrentPages();
				if (pageStack[pageStack.length - 1].route === me.__route__) {
					me.getRoster();
				}
			});
			// 监听被解除好友
			disp.on("em.unsubscribed", function() {
				var pageStack = getCurrentPages();
				if (pageStack[pageStack.length - 1].route === me.__route__) {
					me.getRoster();
				}
			});
			this.setData({
				myName: option.myName,
			});
		},
		mounted() {
			//this.getRoster();
		},
		onShow() {
			this.getRoster();
			//uni.hideHomeButton()
			this.setData({
				messageNum: getApp().globalData.saveFriendList.length,
				unReadSpotNum: getApp().globalData.unReadMessageNum > 99 ?
					"99+" : getApp().globalData.unReadMessageNum,
				unReadNoticeNum: getApp().globalData.saveGroupInvitedList.length,
				unReadTotalNotNum: getApp().globalData.saveFriendList.length +
					getApp().globalData.saveGroupInvitedList.length,
			});

			if (getApp().globalData.isIPX) {
				this.setData({
					isIPX: true,
				});
			}
		},

		methods: {
			getNickName(item) {
				return getApp().globalData.allUsers[item.name].nickname;
			},
			
			getAvatarurl(item) {
				return getApp().globalData.allUsers[item.name].avatarurl;
			
			},
			getRoster() {
				let me = this;
				let rosters = {
					success(roster) {

						console.log("好友", JSON.stringify(roster));
						var users = [];
						var member = [];
						for (let i = 0; i < roster.length; i++) {
							if (roster[i].subscription == "both") {
								users.push(roster[i].name);
							}
						}
						users.push(uni.getStorageSync("myUsername"));

						WebIM.conn.fetchUserInfoById(users, ['nickname', 'avatarurl']).then((res) => {
							console.log("好友数据", res)
							getApp().globalData.allUsers = res.data;
							//alert(JSON.stringify(getApp().globalData.allUsers));
							//globalData: {
							//	allUsers
							for (let i = 0; i < roster.length; i++) {
								if (roster[i].subscription == "both") {

									//var str = "res.data."+roster[i].name+".nickname";
									//roster[i].yournickname =eval(str);

									member.push(roster[i]);
								}
							}

							uni.setStorage({
								key: "member",
								data: member,
							});
							me.setData({
								member: member,
							});

							if (!systemReady) {
								disp.fire("em.main.ready");
								systemReady = true;
							}

							me.getBrands(member);

						})






					},

					error(err) {
						console.log("[main:getRoster]", err);
					},
				};

				WebIM.conn.getRoster(rosters);
			},

			moveFriend: function(message) {
				let me = this;
				let rosters = {
					success: function(roster) {
						var member = [];

						for (let i = 0; i < roster.length; i++) {
							if (roster[i].subscription == "both") {
								member.push(roster[i]);
							}
						}

						me.setData({
							member: member,
						});
					},
				};

				if (message.type == "unsubscribe" || message.type == "unsubscribed") {
					WebIM.conn.removeRoster({
						to: message.from,
						success: function() {
							WebIM.conn.unsubscribed({
								to: message.from,
							});
							WebIM.conn.getRoster(rosters);
						},
					});
				}
			},
			handleFriendMsg: function(message) {
				uni.showModal({
					title: "添加好友请求",
					content: message.from + "请求加为好友",
					success: function(res) {
						if (res.confirm == true) {
							WebIM.conn.subscribed({
								to: message.from,
								message: "[resp:true]",
							});
							WebIM.conn.subscribe({
								to: message.from,
								message: "[resp:true]",
							});
						} else {
							WebIM.conn.unsubscribed({
								to: message.from,
								message: "rejectAddFriend",
							});
						}
					},
					fail: function(err) {},
				});
			},
			delete_friend: function(event) {
				const me = this;
				var delName = event.currentTarget.dataset.username;
				var myName = uni.getStorageSync("myUsername"); // 获取当前用户名

				uni.showModal({
					title: "确认删除好友" + delName,
					cancelText: "取消",
					confirmText: "删除",

					success(res) {
						if (res.confirm == true) {
							WebIM.conn.removeRoster({
								to: delName,
							});
							uni.showToast({
								title: "删除成功",
							});
							// 删除好友后 同时清空会话
							uni.setStorageSync(delName + myName, "");
							uni.setStorageSync("rendered_" + delName + myName, "");
							me.getRoster();
							disp.fire("em.main.deleteFriend");
						}
					},
				});
			},
			openSearch: function() {
				this.setData({
					search_btn: false,
					search_friend: true,
					show_mask: true,
					gotop: true,
				});
			},
			clearInput: function() {
				this.setData({
					input_code: "",
					show_clear: false,
				});
			},
			onInput: function(e) {
				let inputValue = e.detail.value;

				if (inputValue) {
					this.setData({
						show_clear: true,
					});
				} else {
					this.setData({
						show_clear: false,
					});
				}
			},
			cancel: function() {
				this.setData({
					search_btn: true,
					search_friend: false,
					gotop: false, //show_mask: false
				});
				this.getBrands(this.member);
			},
			onSearch: function(val) {
				let searchValue = val.detail.value;
				let member = this.member;
				let serchList = [];
				member.forEach((item, index) => {
					if (String(item.name).indexOf(searchValue) != -1) {
						serchList.push(item);
					}
				});
				this.getBrands(serchList);
			},
			add_new: function() {
				uni.navigateTo({
					url: "../add_new/add_new",
				});
			},
			tab_chat: function() {
				uni.redirectTo({
					url: "../chat/chat",
				});
			},
			close_mask: function() {
				this.setData({
					search_btn: true,
					search_friend: false, //show_mask: false
				});
			},
			tab_setting: function() {
				uni.redirectTo({
					url: "../setting/setting",
				});
			},
			tab_notification: function() {
				uni.redirectTo({
					url: "../notification/notification",
				});
			},
			into_inform: function() {
				uni.navigateTo({
					url: "../inform/inform?myName=" + this.myName, //uni.getStorageSync("myUsername")
				});
			},
			into_groups: function() {
				uni.navigateTo({
					url: "../groups/groups?myName=" + this.myName,
				});
			},
			into_room: function(event) {
				console.log("聊天2", event);
				var nameList = {
					myName: this.myName,
					your: event.target.dataset.username,
					yournickname: event.target.dataset.yournickname,
				};
				console.log("聊天1", JSON.stringify(nameList));
				uni.navigateTo({
					url: "../chatroom/chatroom?username=" + JSON.stringify(nameList),
				});
			},
			into_info: function(event) {
				uni.navigateTo({
					url: "../friend_info/friend_info?yourname=" +
						event.target.dataset.username,
				});
			},
			//点击右侧字母导航定位触发
			scrollToViewFn: function(e) {
				let that = this;
				let _id = e.target.dataset.id;

				for (let i = 0; i < that.listMain.length; ++i) {
					if (that.listMain[i].id === _id) {
						that.setData({
							isActive: _id,
							toView: "inToView" + _id,
						});
						break;
					}
				}
			},

			// 处理数据格式，及获取分组高度
			getBrands: function(member) {
				const that = this;
				const reg = /[a-z]/i;

				member.forEach((item) => {
					if (reg.test(item.name.substring(0, 1))) {
						item.initial = item.name.substring(0, 1).toUpperCase();
					} else {
						item.initial = "#";
					}
				});
				member.sort((a, b) => a.initial.charCodeAt(0) - b.initial.charCodeAt(0));
				var someTtitle = null;
				var someArr = [];

				for (var i = 0; i < member.length; i++) {
					var newBrands = {
						brandId: member[i].jid,
						name: member[i].name,
						yournickname: member[i].yournickname,
					};

					if (member[i].initial == "#") {
						if (!lastObj) {
							var lastObj = {
								id: i,
								region: "#",
								brands: [],
							};
						}

						lastObj.brands.push(newBrands);
					} else {
						if (member[i].initial != someTtitle) {
							someTtitle = member[i].initial;
							var newObj = {
								id: i,
								region: someTtitle,
								brands: [],
							};
							someArr.push(newObj);
						}

						newObj.brands.push(newBrands);
					}
				}

				someArr.sort((a, b) => a.region.charCodeAt(0) - b.region.charCodeAt(0));

				if (lastObj) {
					someArr.push(lastObj);
				}
				//赋值给列表值
				that.setData({
					listMain: someArr,
				}); //赋值给当前高亮的isActive

				that.setData({
					isActive: someArr.length > 0 ? someArr[0].id : "",
				}); //计算分组高度,uni.createSelectotQuery()获取节点信息

				let number = 0;

				for (let j = 0; j < someArr.length; ++j) {
					const query = uni.createSelectorQuery().in(this);
					query
						.select(`#inToView${someArr[j].id}`)
						.boundingClientRect((rect) => {
							if (rect) {
								number = rect.height + number;
								var newArry = [{
									height: number,
									key: rect.dataset.id,
									name: someArr[j].region,
								}, ];
								oHeight = oHeight.concat(newArry);
							} else {
								this.$nextTick(() => {
									//this.getBrands(member)
								});
							}
						})
						.exec();
				}
			},
		},
	};
</script>
<style>
	@import "./main.css";
</style>
